<template>
  <div v-loading="loading" class="order_box gl_mb_20">
    <div class="search_box">
      <el-row :gutter="20">
        <el-col :md="6" :lg="4">
          <p style="font-size: 14px; color: #606266">按订单状态选择</p>
          <el-select v-model="Api_GET_TradePersonalOrderListQO.OrderStatusCode" size="mini" placeholder="请选择订单状态" class="select" @change="getOrder()">
            <el-option label="全部" value="" />
            <el-option v-for="item in orderStatus" :key="item.code" :label="item.value" :value="item.code" />
          </el-select>
        </el-col>
        <el-col :md="6" :lg="4">
          <p style="font-size: 14px; color: #606266">按订单类型选择</p>
          <el-select v-model="Api_GET_TradePersonalOrderListQO.OrderTypeCode" size="mini" placeholder="请选择订单类型" @change="getOrder()">
            <el-option label="全部" value="" />
            <el-option v-for="item in orderTypeList" :key="item.code" :label="item.value" :value="item.code" />
          </el-select>
        </el-col>
        <el-col :md="6" :lg="4">
          <p style="font-size: 14px; color: #606266">按支付方式选择</p>
          <el-select v-model="Api_GET_TradePersonalOrderListQO.ChannelTypeCode" size="mini" placeholder="请选择支付方式" @change="getOrder()">
            <el-option label="全部" value="" />
            <el-option v-for="item in dict.channelType" :key="item.code" :label="item.value" :value="item.code" />
          </el-select>
        </el-col>
      </el-row>
      <div class="gl_mt_15">
        <el-select v-model="searchCode" placeholder="请选择关键词" filterable size="mini" class="select gl_mr_10" style="width:148px" @change="clearSearchText()">
          <el-option value="订单号">订单号</el-option>
          <el-option value="商品名称">商品名称</el-option>
        </el-select>
        <el-input v-model="searchText" placeholder="请输入" size="mini" clearable class="gl_mr_20" @change="getOrder()" />
        <el-select v-model="time" :disabled="true" size="mini" placeholder="请选择时间" class="select gl_mr_10" style="width:148px">
          <el-option value="付款时间">付款时间</el-option>
        </el-select>
        <el-date-picker v-model="paymentTime" type="daterange" size="mini" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd" style="width:400px" @change="timeChange" />
      </div>
    </div>
    <el-divider />
    <form id="form" ref="form" action="https://unipay.ydfuture.com/api/v1/trade/cashDesk" method="post" style="display:none">
      <input ref="pay_params" type="text" name="pay_params" value="">
      <button type="submit">提交</button>
    </form>
    <div v-if="orderList.length > 0">
      <el-button type="primary" size="mini" @click="remove">批量删除</el-button>
      <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" class="gl_mt_15" @change="checkAllChange">
        <div class="head_title">
          <span style="width:260px; text-align:left">订单信息</span>
          <span style="width:110px">付款金额</span>
          <span style="width:130px; text-align:left">物流信息</span>
          <span style="width:80px">线上/线下</span>
          <span style="width:100px">订单类型</span>
          <span style="width:100px">状态</span>
          <span style="width:150px; text-align:left">操作</span>
        </div>
      </el-checkbox>
      <el-checkbox-group v-model="checkedOrder" @change="checkedOrderChange">
        <div v-for="item in orderList" :key="item.id">
          <el-row class="content_head">
            <span>订单号：{{ item.orderNo }}</span>
            <span>下单时间：{{ item.orderDateTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}</span>
            <span v-if="item.payDateTime == '0001-01-01T00:00:00'">付款时间：- -</span>
            <span v-else>付款时间：{{ item.payDateTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}</span>
            <span v-if="item.orderFinishDateTime == '0001-01-01T00:00:00'">完成时间：- -</span>
            <span v-else>完成时间：{{ item.orderFinishDateTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}</span>
            <el-popover v-if="item.orderTypeCode == 'MallOrder'" placement="top" width="300" trigger="hover" :content="item.orderMall[0] && item.orderMall[0].storeName">
              <div slot="reference" style="width:138px;" class="gl_dis_ib gl_ellipsis gl_middle">店铺：{{ (item.orderMall[0] && item.orderMall[0].storeName) || '- -' }}</div>
            </el-popover>
          </el-row>
          <el-checkbox :label="item.orderNo" class="content">
            <div @click.prevent>
              <el-row class="order_content">
                <template v-if="item.orderTypeCode != 'MallOrder'">
                  <div v-if="item.pathImages" class="order_content_img">
                    <img v-if="item.pathImages" :src="getStaticFileUrl(item.pathImages)" alt="" style="width:100%;height:100%">
                  </div>
                  <div v-else class="order_content_img" style="width: 1px" />
                  <div @click="changeRoute(item)">
                    <el-popover class="gl_pl_10" placement="bottom" width="300" trigger="hover" :content="item.name">
                      <div slot="reference" style="width: 210px;" class="gl_ellipsis order_name">{{ item.name }}</div>
                    </el-popover>
                  </div>
                </template>
                <div v-else class="gl_middle">
                  <div v-for="(goods, gIndex) in item.orderMall" :key="gIndex" style="display: block">
                    <div class="order_content_img">
                      <img v-if="goods.productImageUrl" :src="getStaticFileUrl(goods.productImageUrl)" alt="" style="width:100%;height:100%">
                    </div>
                    <div @click="changeRoute(item)">
                      <el-popover class="gl_pl_10" placement="bottom" width="300" trigger="hover" :content="goods.productName">
                        <div slot="reference" style="width:160px;" class="gl_ellipsis order_name">{{ goods.productName }}</div>
                      </el-popover>
                    </div>
                    <div style="width: 50px; text-align:right">X{{ goods.productNum }}</div>
                  </div>
                </div>
                <div class="gl_middle">
                  <div class="line_h gl_middle" style="width:100px">￥{{ (item.payPrice/ 100).toFixed(2) }}</div>
                  <div style="width:130px; text-align:left">
                    <template v-if="item.orderTypeCode == 'MallOrder' && (item.expressName || item.expressInfo)">
                      <p class="gl_ellipsis">{{ item.expressName }}</p>
                      <el-popover placement="bottom" width="300" trigger="hover" :content="item.expressInfo">
                        <div slot="reference" style="width: 130px;" class="gl_ellipsis">{{ item.expressInfo }}</div>
                      </el-popover>
                    </template>
                    <p v-else>无</p>
                  </div>
                  <div class="line_h" style="width:80px">
                    <span v-if="item.isOnlinePayment">线上</span>
                    <span v-else>线下</span>
                  </div>
                  <div class="line_h" style="width:100px">
                    <span v-if="item.orderTypeCode">
                      <template v-for="ktem in dict.orderType">
                        {{ ktem.code === item.orderTypeCode ? ktem.value : '' }}
                      </template>
                    </span>
                  </div>
                  <div class="line_h" style="width:100px">
                    <span v-if="item.orderStatusCode">
                      <template v-for="ktem in dict.orderStatus">
                        {{ ktem.code === item.orderStatusCode ? ktem.value: '' }}
                      </template>
                    </span>
                  </div>
                  <div class="operation">
                    <span style="cursor: pointer;" @click="detail(item.orderNo)">查看详情</span>
                    <span v-if="item.orderStatusCode == 'WAIT_BUYER_PAY'" style="margin:0 10px;color: #d8d8d8;">|</span>
                    <el-dropdown v-if="item.orderStatusCode == 'WAIT_BUYER_PAY'" trigger="click">
                      <span class="el-dropdown-link">
                        更多<i class="el-icon-arrow-down el-icon--right" />
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item v-if="item.orderStatusCode == 'WAIT_BUYER_PAY' && !item.isOnlinePayment" @click.native="showOfflinePayInfo(item.orderNo)">
                          付款方式查看
                        </el-dropdown-item>
                        <el-dropdown-item v-if="item.orderStatusCode == 'WAIT_BUYER_PAY'" @click.native="cancelOrder(item.orderNo)">
                          取消订单
                        </el-dropdown-item>
                        <el-dropdown-item v-if="item.orderStatusCode == 'WAIT_BUYER_PAY' && item.isOnlinePayment" @click.native="payment(item.orderNo)">
                          去支付
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </div>
                </div>
              </el-row>
            </div>
          </el-checkbox>
        </div>
      </el-checkbox-group>
    </div>
    <div v-else class="gl_noData">
      <p>暂无数据</p>
    </div>
    <el-row v-if="orderList.length > 0" class="gl_pt_20" style="text-align: center;">
      <el-pagination :current-page="Api_GET_TradePersonalOrderListQO.Page" :page-size="Api_GET_TradePersonalOrderListQO.MaxResultCount" :total="totalPage" layout="total,sizes,prev,pager,next,jumper" :page-sizes="[10, 20, 50, 100]" @size-change="sizeChange" @current-change="pageIndexChange" />
    </el-row>

    <el-dialog class="gl_dialog_TitleLine" :close-on-click-modal="false" title="线下收款账户信息" :visible.sync="offlineDialogVisible" width="640px">
      <offline-pay-info :offline-data="offlineData" />
      <!-- <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary">{{ $t('button.submit') }}</el-button>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import OfflinePayInfo from '@/components/OfflinePayInfo';
import { mapState, mapActions } from 'vuex';

import {
  // api_GET_TradeOrderDetails, // 根据订单号获取订单详情
  api_GET_TradePersonalOrderCollectionCode, // 获取线下支付订单的收款码信息
  api_GET_TradePersonalOrderList, // 获取订单
  api_PUT_TradeDeletePersonalOrders, // 删除订单
  api_PUT_TradeCancellationOfOrder, // 取消订单
  api_GET_TradePayOrderParameter // 去支付
} from '@/extend/api/swaggerApi/app.js';
import {
  api_GET_EventsManagementCompetitionEntryApprovalCompetitionEntryApprovalSummaryCompetitionId // 赛事信息
} from '@/extend/api/gameswaggerApi/app.js';
import {
  api_GET_TrainTrainningId // 培训信息
} from '@/extend/api/trainswaggerApi/app.js';
import {
  api_GET_MallStoreId // 店铺信息
} from '@/extend/api/shoppingmallswaggerApi/app.js';

import {
  Api_GET_TradePersonalOrderListQO,
  Api_GET_TradePayOrderParameterQO
} from '@/lib/form/swaggerForm';

export default {
  name: 'Order',
  components: {
    OfflinePayInfo
  },
  data() {
    return {
      loading: false,
      searchCode: '订单号',
      searchText: '', // 订单号/商品名称的输入框
      time: '付款时间',
      paymentTime: '', // 付款时间选择器
      currentPage: 1, // 当前页
      totalPage: 0, // 总条目数
      checkAll: false, // 全选
      checkedOrder: [], // 选中的订单
      isIndeterminate: false,
      orderList: [], // 订单列表
      orderStatus: [], // 订单状态下拉列表
      orderTypeList: [], // 订单类型下拉列表
      action: 'https://unipay.ydfuture.com/api/v1/trade/cashDesk', // 支付地址
      Api_GET_TradePersonalOrderListQO: new Api_GET_TradePersonalOrderListQO(),
      Api_GET_TradePayOrderParameterQO: new Api_GET_TradePayOrderParameterQO(),
      offlineDialogVisible: false,
      offlineData: {} // 线下支付信息数据
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  created() {
    // 获取字典
    this.getDict().then(res => {
      this.orderStatus = res.orderStatus.filter((item) => {
        return item.code !== 'TRADE_SUCCESS';
      });
      this.orderTypeList = res.orderType.filter((item) => {
        return item.code !== 'VoteOrder' && item.code !== 'ClubStudentMembershipCardOrder' && item.code !== 'SystemOrder';
      });
    });
    // 报名生成订单后跳转到订单页
    if (this.$route.query.out_trade_no) {
      this.searchText = this.$route.query.out_trade_no;
      this.Api_GET_TradePersonalOrderListQO.OrderNo = this.$route.query.out_trade_no;
    }
    this.getOrder();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 获取订单数据
    getOrder(page) {
      var that = this;
      that.loading = true;
      if (that.searchCode === '订单号') {
        that.Api_GET_TradePersonalOrderListQO.OrderNo = that.searchText;
        that.Api_GET_TradePersonalOrderListQO.OrderName = '';
      } else {
        that.Api_GET_TradePersonalOrderListQO.OrderName = that.searchText;
        that.Api_GET_TradePersonalOrderListQO.OrderNo = '';
      }
      that.Api_GET_TradePersonalOrderListQO.Sorting = 'CreationTime Desc';
      that.Api_GET_TradePersonalOrderListQO.Page = page || 1;
      that.Api_GET_TradePersonalOrderListQO.SkipCount =
        (that.Api_GET_TradePersonalOrderListQO.Page - 1) *
        that.Api_GET_TradePersonalOrderListQO.MaxResultCount;
      api_GET_TradePersonalOrderList(that.Api_GET_TradePersonalOrderListQO)
        .then(res => {
          that.orderList = res.items;
          that.totalPage = res.totalCount;
          that.loading = false;
        }).catch(() => {
          that.loading = false;
        });
    },
    clearSearchText() {
      this.searchText = '';
      this.getOrder();
    },
    // 点击赛事标题进行路由跳转
    changeRoute(item) {
      if (item.orderCompetition.length > 0) {
        api_GET_EventsManagementCompetitionEntryApprovalCompetitionEntryApprovalSummaryCompetitionId(item.providerKey).then(res => {
          const competition = res.competition;
          var a = document.createElement('a');
          var event = new MouseEvent('click');
          a.href = `${location.origin}/game.html#/home/${competition.route}/info`;
          a.target = '_blank';
          a.dispatchEvent(event);
        });
      } else if (item.orderTraining.length > 0) {
        const id = item.orderTraining[0].trainingId;
        api_GET_TrainTrainningId(id).then(res => {
          const training = res;
          var a = document.createElement('a');
          var event = new MouseEvent('click');
          a.href = `${location.origin}/train.html#/home/${training.route + (training.tenantId ? '_' + training.tenantId : '')}/info`;
          a.target = '_blank';
          a.dispatchEvent(event);
        });
      } else if (item.orderMall.length > 0) {
        const id = item.orderMall[0].storeId;
        api_GET_MallStoreId(id).then(res => {
          const store = res;
          var a = document.createElement('a');
          var event = new MouseEvent('click');
          a.href = `${location.origin}/mall.html#/home/${store.route + (store.tenantId ? '_' + store.tenantId : '') + '_plat'}/info`;
          a.target = '_blank';
          a.dispatchEvent(event);
        });
      }
    },
    // 图片回显
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 付款日期选择器
    timeChange(val) {
      if (val instanceof Array) {
        this.Api_GET_TradePersonalOrderListQO.PaymentStartDate = this.paymentTime[0];
        this.Api_GET_TradePersonalOrderListQO.PaymentEndDate = this.paymentTime[1];
      } else {
        this.Api_GET_TradePersonalOrderListQO.PaymentStartDate = '';
        this.Api_GET_TradePersonalOrderListQO.PaymentEndDate = '';
      }
      this.getOrder(this.Api_GET_TradePersonalOrderListQO.Page);
    },
    // 全选
    checkAllChange(val) {
      const idList = this.orderList.map(item => {
        return item.orderNo;
      });
      this.checkedOrder = val ? idList : [];
      this.isIndeterminate = false;
    },
    // 多选
    checkedOrderChange(value) {
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.orderList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.orderList.length;
    },
    // 删除所选订单
    remove() {
      if (this.checkedOrder.length > 0) {
        const data = [];
        // 只能删除已取消的订单
        for (let i = 0; i < this.checkedOrder.length; i++) {
          data.push({ orderNo: this.checkedOrder[i] });
          for (const j in this.orderList) {
            if (this.orderList[j].orderNo === this.checkedOrder[i]) {
              if (this.orderList[j].orderStatusCode !== 'TRADE_CLOSED') {
                this.$message({
                  type: 'warning',
                  message:
                    '【' + this.orderList[j].orderNo + '】订单状态不是已取消，不可删除'
                });
                return false;
              }
              break;
            }
          }
        }
        var that = this;
        this.$confirm('您确定要删除所选订单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          that.loading = true;
          api_PUT_TradeDeletePersonalOrders(data).then(res => {
            that.$message({
              type: 'success',
              message: '删除成功!'
            });
            that.getOrder(that.Api_GET_TradePersonalOrderListQO.Page);
            that.loading = false;
          }).catch(() => {
            that.loading = false;
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除'
          });
        });
      } else {
        this.$message({
          type: 'warning',
          message: '请先选择订单！'
        });
      }
    },
    // 去支付
    payment(id) {
      var that = this;
      if (id) {
        // var href = window.location.href;
        // var url = href.split('?');
        // var returnUrl = url[0].substring(0, url[0].length - 5);
        const _origin = window.location.origin;
        const _pathname = window.location.pathname;
        const _orderUrl = '#/myCenter/order/main';
        const url = _origin + _pathname + _orderUrl;
        that.Api_GET_TradePayOrderParameterQO.OrderNo = id;
        that.Api_GET_TradePayOrderParameterQO.ReturnUrl = url; // 支付成功后跳转的地址
        api_GET_TradePayOrderParameter(that.Api_GET_TradePayOrderParameterQO).then(res => {
          this.$refs.pay_params.value = res.parameter.replace(/\s*/g, '');
          this.$refs.form.submit();
        }).catch(error => {
          this.$message({
            type: 'error',
            message: error.error.message
          });
        });
      }
    },
    // 取消订单
    cancelOrder(id) {
      var that = this;
      this.$confirm('您确定要取消订单吗?', '取消订单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          that.loading = true;
          const data = { orderNo: id };
          api_PUT_TradeCancellationOfOrder(data).then(res => {
            that.$message({
              type: 'success',
              message: '取消成功!'
            });
            that.loading = false;
            that.getOrder(that.Api_GET_TradePersonalOrderListQO.Page);
          }).catch((error) => {
            that.loading = false;
            that.$message({ type: 'error', message: error.error.message || '操作失败' });
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '放弃取消'
          });
        });
    },
    // 查看详情
    detail(id) {
      this.$router.push({
        path: '/myCenter/order/detail',
        query: { id: id }
      });
    },
    // 付款方式查看
    showOfflinePayInfo (orderNo, data) {
      this.getOrderDetails(orderNo);
    },
    // 获取订单详情，用于线下支付展示收款账户信息
    getOrderDetails (orderNo) {
      this.loading = true;
      api_GET_TradePersonalOrderCollectionCode({ orderNo: orderNo })
        .then(
          res => {
            this.loading = false;
            res._orderNo = orderNo;
            this.offlineData = res;
            this.offlineDialogVisible = true;
          }
        ).catch(error => {
          this.loading = false;
          this.$message({
            type: 'error',
            message: error.error.message
          });
        }
        );
    },
    // 分页
    sizeChange: function(MaxResultCount) {
      this.Api_GET_TradePersonalOrderListQO.MaxResultCount = MaxResultCount; // 每页显示条目数
      this.getOrder();
    },
    pageIndexChange(currentPage) {
      this.getOrder(currentPage);
    }
  }
};
</script>

<style scoped>
.order_box {
  padding: 2px;
  font-size: 16px;
}
.select {
  /* width: 224px; */
  /* height: 40px; */
  color: #353434;
}
.el-input {
  width: 190px;
  /* height: 40px; */
}
.el-checkbox {
  width: 100%;
  background: #fafafa;
  cursor: default;
}
.el-checkbox /deep/ .el-checkbox__input {
  margin-left: 20px;
}
.head_title {
  width: 100%;
  height: 54px;
  background: #fafafa;
  border-radius: 4px 4px 0px 0px;
  font-size: 14px;
  text-align: center;
  line-height: 54px;
  /* padding: 0 24px; */
  color: #000;
}
.head_title span {
  display: inline-block;
}
.content {
  width: 100%;
  background-color: #ffffff;
}
.el-checkbox /deep/ .el-checkbox__label {
  width: 96%;
}
.content_head {
  width: 100%;
  line-height: 38px;
  background: #eaf5ff;
  padding-left: 20px;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.85);
}
.content_head span {
  margin-right: 15px;
}
.order_content_img {
  width: 48px;
  height: 48px;
  border-radius: 4px;
  vertical-align: middle;
  overflow: hidden;
  margin: 10px 0;
}
.order_content div {
  display: inline-block;
}
.line_h {
  text-align: center;
}
.operation {
  text-align:left;
  color: #1890ff;
}
.operation_icon {
  margin-left: 4px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.el-dropdown-menu__item {
  min-width: 120px;
}
.order_name {
  vertical-align: middle;
  cursor: pointer;
}
.order_name:hover{
  color: #1890ff;
  text-decoration: underline;
}
</style>
